﻿namespace sfcms.api
{
    using System;
    using System.Data;

    public abstract class child
    {
        private folder _parent;
        public long id;

        protected child()
        {
        }

        public void setparent(long parentID)
        {
            if (this.id == 0L)
            {
                throw new InvalidOperationException("The item should be saved first");
            }
            if (parentID != 0L)
            {
                folder testfolder = folder.byid(parentID);
                if (testfolder == null)
                {
                    throw new InvalidOperationException("Invalid folder");
                }
                if (((this is page) && (testfolder.type != 1)) || ((this is file) && (testfolder.type != 2)))
                {
                    throw new InvalidOperationException("Invalid folder, the parent folder is not a appropriate folder");
                }
            }
            if (this is page)
            {
                new database().ExecuteNonQuery("DELETE SFCMS_PagePath WHERE PageID = @0\r\nINSERT INTO SFCMS_PagePath (PageID, ParentID) VALUES (@0, @1)", new object[] { database.CreateTypedParameterName("@0", DbType.Int64), this.id, database.CreateTypedParameterName("@1", DbType.Int64), parentID });
            }
            else
            {
                new database().ExecuteNonQuery("DELETE SFCMS_FilePath WHERE FileID = @0\r\nINSERT INTO SFCMS_FilePath (FileID, ParentID) VALUES (@0, @1)", new object[] { database.CreateTypedParameterName("@0", DbType.Int64), this.id, database.CreateTypedParameterName("@1", DbType.Int64), parentID });
            }
        }

        public folder parent
        {
            get
            {
                if (this.id == 0L)
                {
                    return null;
                }
                if (this._parent == null)
                {
                    long folderID = Convert.ToInt64(new database().ExecuteScalar("SELECT ParentID FROM SFCMS_PagePath (NOLOCK) WHERE PageID = @0", new object[] { "@0", this.id }));
                    this._parent = folder.byid(folderID);
                }
                return this._parent;
            }
        }
    }
}

